const _ = require('lodash');
const moment = require("moment");
//moment.tz.setDefault('Asia/Shanghai')

module.exports = class {
    constructor(app) {
        this.app = app;
        this.subDeviceData = data => {
            data && this.onData(data);
            return 'ok';
        };
        this.app.eventBus.on('HTTP_DATA_RECEVED', this.subDeviceData);
        // const inv = setInterval(async () => {
        //     const list = await this.app.dbs.find("IotDevice", {});
        //     _.map(list, async device => {
        //         const {deviceId, points, tenantCode} = device;
        //         const dev = await this.app.dbs.findOne('DeviceCache', {deviceId, tenantCode});
        //         delete device["_id"];
        //
        //         if (dev === null && points) {
        //             device.time = moment().valueOf();
        //             //  console.log('insert DeviceCache', device.deviceId, status);
        //             await this.app.dbs.insert("IotReportData", device);
        //             await this.app.dbs.insert("DeviceCache", device);
        //         } else {
        //             let isChange = false;
        //             _.map(points, (value, key) => {
        //                 if (key !== "time" && key !== "dataTime" && dev.points && value !== dev.points[key]) {
        //                     isChange = true;
        //                 }
        //             });
        //             if (isChange) {
        //                 await this.app.dbs.insert("IotReportData", device);
        //                 await this.app.dbs.updateOne("DeviceCache", {deviceId}, device);
        //             }
        //         }
        //     });
        // }, 5 * 1000);
    }

    async onData(data) {
        const {topic, payload} = data;
        let deviceId = topic.replace('/databack/iotReport', '');
        deviceId = deviceId.replace('/databack', '');
        deviceId = deviceId.replace('/iotReport', '');
        const device = await this.app.dbs.findOne("IotDevice", {deviceId}, null);
        if (!device) return false;
        delete device._id;
        const {statusPath, points, tenantCode} = device;
        const _status = payload[statusPath];
        const time = moment().valueOf();
        const uid = deviceId + "-" + moment().format("YYYY-MM-DD-HH:mm:ss");
        /**
         * 更新影子数据
         */
        if(deviceId==='ptyhHotMeter'){
            console.log('ptyhHotMeter',payload)
        }
        const upRes = await this.app.dbs.updateOne("IotDevice", {deviceId, tenantCode}, {
            status: _status,
            points: payload,
            time: new moment().valueOf(),
            uid
        });
        // console.log('更新iot device', upRes);
        /**
         * 检查是不是有变化
         */
        device.time = time;
        device.uid = uid;
        device.status = _status;

        if (!points) {
            device.points = payload;
            console.log('插入iot device', upRes);
            return await this.app.dbs.insert("IotReportData", device);
        }

        let isChange = false;
        // console.log('payload', payload);
        _.map(payload, (value, key) => {
            //   console.log('key', key, 'value', value,'points[key]',points[key]);
            if (key !== 'dataTime' && points[key] !== value) {
                isChange = true;
            }
        });

        if (isChange) {
            //  console.log('更新设备：' + deviceId);
            return await this.app.dbs.insert("IotReportData", device);
        }
     //   console.log('数据没有变化', device.deviceName);
        return true;

    }

    async destroy() {
        //    this.app.eventBus.removeListener(this.httpBus, this.subDeviceData);

        return 'ok';
    }


};
